﻿import shelve
import os

class DataBase(object):
    def __init__(self, database_name, remove):
        self.__next_id = 0
        self.__database = None
        
        if remove:
            self.__remove(database_name)
        
        self.__open(database_name)
        
    def __remove(self, name):
        try:
            os.remove(name)
        except:
            pass
        
    def __open(self, name):
        try:
            self.__database = shelve.open(name)
            self.__find_next_id()
        except Exception as e:
            pass
        
    def __find_next_id(self):
        try:
            keys = self.__database.keys()
            self.__next_id = len(keys)
        except:
            pass
        
    def get_next_id(self):
        return str(self.__next_id)
        
    def insert(self, element):
        self.__database[self.get_next_id()] = element
        self.__find_next_id()
        
    def get_element(self, id):
        id = str(id)
        if self.__database.has_key(id):
            return self.__database[id]        
        
    def get_elements(self):
        return self.__database.values()
                
    def close(self):
        self.__database.close() 